package com.module.framework.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.module.framework.domain.Comment;
import com.module.framework.domain.CommentList;
import com.module.framework.domain.LoginUser;
import com.module.framework.domain.Menu;
import com.module.framework.mapper.CommentMapper;
import com.module.framework.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<List<Comment>> commentList(Integer pageNum, Integer pageSize) {
        pageNum = (pageNum - 1) * pageSize;
        List<Comment> lists = commentMapper.selectByIdList(pageNum, pageSize);
        List<List<Comment>> result = lists.stream()
                .collect(Collectors.groupingBy(Comment::getBookId))
                .values().stream()
                .collect(Collectors.toList());

        return result;
    }

    @Override
    public CommentList getCommentInfo(Integer id) {
        CommentList commentList = new CommentList();
        List<Comment> comment1 = commentMapper.selectByIdVO(id);
        List<String> strings = new ArrayList<>();
        for (Iterator<Comment> iterator = comment1.iterator(); iterator.hasNext(); ) {
            Comment next = iterator.next();
            strings.add(next.getComment());
        }
        commentList.setComment(strings);
        commentList.setName(comment1.get(0).getName());
        commentList.setAuthor(comment1.get(0).getAuthor());
        commentList.setCategoryName(comment1.get(0).getCategoryName());
        return commentList;
    }

    @Override
    public void addComment(Integer bookId, String comment) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();

        Comment comment1 = new Comment();
        comment1.setComment(comment);
        comment1.setUserId(userId);
        comment1.setBookId(bookId);
        commentMapper.insert(comment1);
    }
    @Override
    public boolean deleteComment(Integer id) {
        // 检查是否存在该评论
        Comment comment = commentMapper.selectById(id);
        if (comment != null) {
            // 删除评论
            int result = commentMapper.deleteById(id);
            return result > 0;
        }
        return false;
    }
}
